
const state = {
  carList: []
}

const mutations = {
  setItem(state, payload) {
    // state.carList = JSON.parse(localStorage.getItem('carList')) ? JSON.parse(localStorage.getItem('carList')) : state.carList;
    let result = state.carList.find(item => item.id === payload.productId);
    if (result) {
      result.quantity++;
    } else {
      state.carList.push({
        id: payload.productId,
        quantity: 1,
        ischecked: false,
        product: payload
      })
    }
    console.log(state.carList);
    localStorage.setItem('carList', JSON.stringify(state.carList))
  },
  changeItem(state, payload) {
    // console.log(payload);
    state.carList[payload.index].quantity = payload.value;
    localStorage.setItem('carList', JSON.stringify(state.carList))
  },
  checkAll(state, payload) {
    // console.log(payload);
    state.carList[payload].ischecked = !state.carList[payload].ischecked;
    localStorage.setItem('carList', JSON.stringify(state.carList))
  },
  checkAllGoods(state, payload) {
    if (payload) {state.carList = state.carList.map(item => {
      item.ischecked = true;
      return item;
    })}else{
      state.carList=state.carList.map(item=>{
        item.ischecked=false;
        return item;
      })
    }
    localStorage.setItem('carList', JSON.stringify(state.carList))
  },
  delItem(state, payload){
    // console.log(state.carList,payload);
    state.carList.splice(payload,1);
    localStorage.setItem('carList', JSON.stringify(state.carList))
  }
}

const actions = {
  asetItem({ commit }, payload) {
    commit('setItem', payload)
  },
  achangeItem({ commit }, payload) {
    commit('changeItem', payload)
  },
  acheckAll({ commit }, payload) {
    commit('checkAll', payload)
  },
  acheckAllGoods({ commit }, payload) {
    commit('checkAllGoods', payload)
  },
  adelItem({ commit }, payload) {
    commit('delItem', payload)
  }
}

const getters = {
  totlePrice(state) {
    state.carList = JSON.parse(localStorage.getItem('carList')) ? JSON.parse(localStorage.getItem('carList')) : state.carList;
    return state.carList.reduce((value, item, index) => {
      if (item.ischecked === true) value += item.product.priceDisplay.currentPrice * item.quantity;
      return value;
    }, 0);
  },
  checkedAll(state) {
    // state.carList=JSON.parse(localStorage.getItem('carList'))?JSON.parse(localStorage.getItem('carList')):state.carList;
    return state.carList.every(item => item.ischecked)
  }
}

export default {
  // namespaced: true,
  state,
  mutations,
  actions,
  getters
}